/*
 * @Description: 档案管理权限规则 - 创建规则弹窗 上下文
 * @Author: Rfan
 * @Date: 2022-04-06 13:13:27
 * @LastEditTime: 2022-04-15 15:32:18
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { ExpGeneratorDialogReducer } from '../reducers/ExpGeneratorDialogReducer';
import {
  ADD_CONDITION_ITEM,
  CLEAR_CONDITION_LIST,
  DELETE_LAST_CONDITION_ITEM,
  RESET_DIALOG,
  SET_FIELD_LIST
} from '../constants';
import { jsonClone } from '@/utils';

const initialState = {
  // 字段列表
  fieldList: [],
  // 条件列表
  conditionList: []
};

const ExpGeneratorDialogContext = createContext();

const ExpGeneratorDialogContextProvider = (props) => {
  const [state, dispatch] = useReducer(ExpGeneratorDialogReducer, initialState);

  const actions = {
    /**
     * @description: 添加条件条目
     * @param {*} 要添加的条目
     */
    addConditionItem(params) {
      const data = jsonClone(params);
      data.id = uuidv4();
      dispatch({ type: ADD_CONDITION_ITEM, data });
    },
    /**
     * @description: 删除最后一条条目
     */
    deleteLastConditionItem() {
      dispatch({ type: DELETE_LAST_CONDITION_ITEM });
    },

    /**
     * @description: 清空所有条件
     */
    clearConditionList() {
      dispatch({ type: CLEAR_CONDITION_LIST });
    },

    /**
     * 获取field选项
     */
    getFieldList(query) {
      console.log('getFieldList: ', query);
      const data = [
        { id: 0, field_desc: '全宗号', field_name: 'FONDCODE', field_type: 0 },
        { id: 1, field_desc: '流水号', field_name: 'SERIALNO', field_type: 1 },
        { id: 2, field_desc: '档号', field_name: 'ARCNO', field_type: 0 },
        { id: 3, field_desc: '题名', field_name: 'TITLE', field_type: 0 }
      ];
      // searchFetchFields(query)
      //   .then(res => {
      //     const data = res.data;
      //     dispatch({ type: SET_FIELD_LIST, data });
      //   });
      dispatch({ type: SET_FIELD_LIST, data });
    },

    /**
     * @description: 重置弹窗
     */
    resetDialog() {
      dispatch({ type: RESET_DIALOG });
    }
  };

  // watch选中的单位来加载全宗
  useEffect(() => {}, []);

  return (
    <ExpGeneratorDialogContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </ExpGeneratorDialogContext.Provider>
  );
};

export const useExpGeneratorDialogContext = () => {
  return useContext(ExpGeneratorDialogContext);
};

export { ExpGeneratorDialogContext, ExpGeneratorDialogContextProvider };
